package self.security.config;

import org.self.service.IJwtService;
import org.self.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import self.security.filter.AuthFilter;
import self.security.filter.LoginFilter;

@SpringBootConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private LogoutHandler logoutHandler;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IJwtService jwtService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .and()
                .cors()  //跨域不使能
                .and()
                .csrf()  //防止跨站点伪造我使能
                .disable();

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint) //这个配置的是没有权限访问的时候的处理器是谁
                .and()
                .logout()
                .logoutUrl("/user/logout")         //这个表示的是配置的是退出这个功能的处理路径是啥
                .addLogoutHandler(logoutHandler)
                .and()
                .addFilter(new LoginFilter(authenticationManager(), tokenService))  //添加了登陆的处理的过滤器
                .addFilter(new AuthFilter(authenticationManager(), tokenService, jwtService))  //添加的是认证的这个过滤器
                .httpBasic();
        super.configure(http);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //在这个方法中更多的是配置的不拦截的路径有哪些
        web.ignoring().antMatchers("/liYu/xxx");

        //所需要用到的静态资源，允许访问
        web.ignoring().antMatchers("/swagger-ui.html",
                "/swagger-ui/*",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**");

    }

}
